﻿using System.Collections.Generic;
using Microsoft.VisualStudio.Debugger.Interop;
using Red.Scripts.Debugger.Defines;

namespace Red.Scripts.Debugger.Engine.Breakpoint
{
    public class Manager
    {
        #region Private Data

        private IProgram _debuggedProgram;
        private List<Pending> _breakpoints = new List<Pending>();

        #endregion Private Data

        #region Public Properties

        public IProgram DebuggedProgram
        {
            get { return _debuggedProgram; }
            set { UpdatePending( value ); }
        }

        #endregion Public Properties

        #region Public Methods

        public IDebugPendingBreakpoint2 Create( IDebugBreakpointRequest2 request )
        {
            Pending pending = new Pending( request ) { DebuggedProgram = DebuggedProgram };
            _breakpoints.Add( pending );

            pending.Deleted += Pending_Deleted;

            return pending;
        }

        public void Rebind()
        {
            foreach ( Pending breakpoint in _breakpoints )
            {
                ((IDebugPendingBreakpoint2)breakpoint).Bind();
            }
        }

        #endregion Public Methods

        #region Private Methods

        private void UpdatePending( IProgram debuggedProgram )
        {
            if ( _debuggedProgram != debuggedProgram )
            {
                _debuggedProgram = debuggedProgram;

                foreach ( Pending breakpoint in _breakpoints )
                {
                    breakpoint.DebuggedProgram = debuggedProgram;
                }
            }
        }

        #endregion Private Methods

        #region Event Handlers

        private void Pending_Deleted( object sender, System.EventArgs e )
        {
            Pending pending = (Pending)sender;
            pending.Deleted -= Pending_Deleted;

            _breakpoints.Remove( pending );
        }

        #endregion Event Handlers
    }
}
